﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NHibernate.Criterion;
using ZDSoft.TES.Entity.SystemEntity;
using ZDSoft.TES.Core;
using ZDSoft.TES.Service.SystemService;
using ZDSoft.TES.Web.Helpers;

namespace ZDSoft.TES.Web.Controllers
{
    public class UserController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public void Create(string Account, string Password, string UserName, string IsActive, string selectedIds, string selectedOIds)
        {
            string[] ids = selectedIds.Split(',');
            IList<Role> selectedRoles = new List<Role>();
            foreach (string i in ids)
            {
                if (i != "undefined" && i != "")
                {
                    selectedRoles.Add(Container.Instance.Resolve<IRoleService>().FindByID(int.Parse(i.Substring(4))));
                }
            }
            Organization org = Container.Instance.Resolve<IOrganizationService>().FindByID(int.Parse(selectedOIds));
            User user = new User() { Account = Account, UserName = UserName, Password = Password, IsActive = bool.Parse(IsActive), IsReset = false, Roles = selectedRoles, Organization = org };
            Container.Instance.Resolve<IUserService>().Create(user);
        }

        public ActionResult Update(int id)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Update(string Account, string Password, string IsActive, string selectedIds, string selectedOIds, int id)
        {
            User user = Container.Instance.Resolve<IUserService>().FindByID(id);
            user.Account = Account;
            user.Password = Password;
            user.IsActive = bool.Parse(IsActive);
            user.Roles = null;
            user.Roles = new List<Role>();
            user.Organization = null;
            string[] ids = selectedIds.Split(',');
            IList<string> roleIDs = new List<string>();
            IList<Role> selectedRoles = new List<Role>();
            IList<string> userManager = new List<string>();
            foreach (string i in ids)
            {
                if (i != "undefined" && i != "")
                {
                    string[] tmp = i.Split('|');
                    if (tmp.Length == 1 && !roleIDs.Contains(tmp[0].Substring(4)))
                    {
                        roleIDs.Add(tmp[0].Substring(4));
                    }
                    else if (tmp.Length == 2)
                    {
                        userManager.Add(tmp[1].Substring(6));
                    }
                }
            }
            foreach (string i in roleIDs)
            {
                selectedRoles.Add(Container.Instance.Resolve<IRoleService>().FindByID(int.Parse(i)));
            }
            user.Roles = selectedRoles;
            user.Organization = Container.Instance.Resolve<IOrganizationService>().FindByID(int.Parse(selectedOIds));
            Container.Instance.Resolve<IUserService>().Update(user);
            return View();
        }

        [HttpPost]
        public void Withdraw(int id)
        {
            User user = Container.Instance.Resolve<IUserService>().FindByID(id);
            if (user.IsActive == true)
            {
                user.IsActive = false;
            }
            else
            {
                user.IsActive = true;
            }
            Container.Instance.Resolve<IUserService>().Update(user);
        }
        public string GetUserByID(int id)
        {
            User user = Container.Instance.Resolve<IUserService>().FindByID(id);
            IList<KeyValuePair<string, InvokeMethod>> list = new List<KeyValuePair<string, InvokeMethod>>();
            //list.Add(new KeyValuePair<string, InvokeMethod>("xx", GetUsers));
            string str = user.ToJsonString<User>(list);
            return str;
        }


        public JsonResult GetAllRoles(int id, int pid, string name, int level)
        {
            IList<Role> roles = Container.Instance.Resolve<IRoleService>().FindAll();
            IList<ZTreeHelper<Role>.ZTreeNode> tree = new List<ZTreeHelper<Role>.ZTreeNode>();
            foreach (Role role in roles)
            {
                int tmpID = int.Parse(id.ToString() + role.ID.ToString());
                ZTreeHelper<Role>.ZTreeNode node = new ZTreeHelper<Role>.ZTreeNode();
                node.id = tmpID;
                node.pid = id;
                node.tld = "role" + role.ID;
                node.name = role.RoleName;
                tree.Add(node);
            }
            JsonResult json = this.Json(tree, JsonRequestBehavior.AllowGet);
            return json;
        }

        public JsonResult GetAllOrganizations(int id, int pid, string name, int level)
        {
            IList<Organization> Organizations = Container.Instance.Resolve<IOrganizationService>().FindAll();
            IList<ZTreeHelper<Organization>.ZTreeNode> tree = new List<ZTreeHelper<Organization>.ZTreeNode>();
            foreach (Organization org in Organizations)
            {
                int tmpID = int.Parse(id.ToString() + org.ID.ToString());
                ZTreeHelper<Organization>.ZTreeNode node = new ZTreeHelper<Organization>.ZTreeNode();
                node.id = tmpID;
                node.pid = id;
                node.tld = "org" + org.ID;
                node.name = org.OrganizationName;
                tree.Add(node);
            }
            JsonResult json = this.Json(tree, JsonRequestBehavior.AllowGet);
            return json;
        }


        public JsonResult GetPaged(int pageIndex, int pageSize, string strSearchProperty,
            string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<User> list = new List<User>();
            IList<User> users = Container.Instance.Resolve<IUserService>().GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);

            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }
            foreach (User user in users)
            {
                User userJson = user.ToJaonResult<User>();
                list.Add(userJson);
            }
            list.Add(new User() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }
    }
}
